<template>
  <el-drawer v-model="drawerVisible" direction="rtl" @open="handleOpen" @close="handleClose">
    <template #header>
      <h2 style="font-weight: bold">角色权限管理</h2>
    </template>
    <template #default>
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="data"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
      />
    </template>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ElTree } from 'element-plus'
import { useRoleStore } from '@/stores/role/role.js'
import { storeToRefs } from 'pinia'
import { ref } from 'vue'

const roleStore = useRoleStore()
const { drawerVisible, sysNodes } = storeToRefs(roleStore)

const defaultProps = {
  children: 'children',
  label: 'title'
}
const data = sysNodes
const treeRef = ref(null)

const cancelClick = () => {
  roleStore.setDrawerVisible(false)
}
const confirmClick = () => {
  // roleStore.getSysNodes()
  // console.log('checkedNodes:' + treeRef.value.getCheckedKeys())
  const half = treeRef.value.getHalfCheckedKeys()
  const checked = treeRef.value.getCheckedKeys()
  //合并数组
  const all = [...half, ...checked]
  roleStore.updateAuth(all)
}

const handleOpen = () => {
  // console.log('DrawerTree')
  roleStore.getSysNodes()
  //等待一段时间
  setTimeout(() => {
    // console.log('treeRef:' + treeRef.value)
    roleStore.getNodeById(roleStore.role.roleId, treeRef)
  }, 500)
}
const handleClose = () => {
  // console.log('handleClose')
  roleStore.setSelectedNodes([])
  treeRef.value.setCheckedKeys([])
}
</script>

<style scoped lang="scss">
.drawer-footer {
  display: flex;
  justify-content: space-between;
  margin-left: 50px;
  margin-right: 50px;
  margin-bottom: 50px;
}
</style>
